package com.forum.service.impl;

import com.forum.common.event.LikeEvent;
import com.forum.common.event.MessageEventPublisher;
import com.forum.common.model.entity.Like;
import com.forum.mapper.LikeMapper;
import com.forum.mapper.PostMapper;
import com.forum.model.entity.Post;
import com.forum.service.LikeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 点赞服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LikeServiceImpl implements LikeService {
    
    private final LikeMapper likeMapper;
    private final PostMapper postMapper;
    // 注入消息事件发布服务
    private final MessageEventPublisher messageEventPublisher;
    
    /**
     * 帖子类型
     */
    private static final int TYPE_POST = 1;
    
    /**
     * 评论类型
     */
    private static final int TYPE_COMMENT = 2;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean like(Long userId, Long targetId, Integer type) {
        // 查询是否已点赞
        Like like = likeMapper.findByUserIdAndTargetIdAndType(userId, targetId, type);
        
        if (like != null) {
            // 已点赞，取消点赞
            likeMapper.deleteByUserIdAndTargetIdAndType(userId, targetId, type);
            
            // 如果是帖子，减少帖子点赞数
            if (TYPE_POST == type) {
                decrementPostLikes(targetId);
            }
            
            return false;
        } else {
            // 未点赞，添加点赞
            like = new Like();
            like.setUserId(userId);
            like.setTargetId(targetId);
            like.setType(type);
            like.setCreatedAt(LocalDateTime.now());
            likeMapper.insert(like);
            
            // 如果是帖子，增加帖子点赞数
            if (TYPE_POST == type) {
                incrementPostLikes(targetId);
                
                // 发送点赞消息通知帖子作者
                try {
                    // 获取帖子信息
                    Post post = postMapper.selectById(targetId);
                    if (post != null && !userId.equals(post.getUserId())) { // 不给自己发通知
                        LikeEvent event = LikeEvent.postLike(
                            userId,              // 发送者（点赞用户）
                            post.getUserId(),    // 接收者（帖子作者）
                            targetId,            // 关联资源ID（帖子ID）
                            post.getTitle()      // 帖子标题
                        );
                        messageEventPublisher.publishLikeEvent(event);
                        log.info("帖子点赞消息发送成功");
                    }
                } catch (Exception e) {
                    log.error("帖子点赞消息发送失败: {}", e.getMessage(), e);
                    // 消息发送失败不影响主流程
                }
            }
            // TODO: 如果是评论，也可以发送点赞通知
            
            return true;
        }
    }
    
    @Override
    public boolean hasLiked(Long userId, Long targetId, Integer type) {
        return likeMapper.existsByUserIdAndTargetIdAndType(userId, targetId, type) > 0;
    }
    
    @Override
    public int getLikeCount(Long targetId, Integer type) {
        return likeMapper.countByTargetIdAndType(targetId, type);
    }
    
    /**
     * 增加帖子点赞数
     */
    private void incrementPostLikes(Long postId) {
        postMapper.incrementLikes(postId);
    }
    
    /**
     * 减少帖子点赞数
     */
    private void decrementPostLikes(Long postId) {
        postMapper.decrementLikes(postId);
    }
} 